const app = getApp()
const wxpay = require('../../utils/pay.js')
const CONFIG = require('../../config.js')
const WXAPI = require('../../wxapi/main')
import Toast from 'tdesign-miniprogram/toast/index';
const dateUtil = require('../../utils/date')
const defaultAvatarUrl="https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0"
Page({
  data: {
    select: ["select", "", ""],
    display: ["display", "hidden", "hidden"],
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    nickName: "",
    window_display: "none",
    msgCode: '',
    serviceNum: '',
    codeDesc: '免费获取',
    loginTip: '',
    login_disabled: 'disabled',
    userId: "",
    integralCount: "",
    hasWelfareInfo: "",
    avatarUrl: defaultAvatarUrl,
    isVip: false,
    isManager: true,
    userInfo: {},
    haveCoupons:false,
      title: "个人中心", // 导航栏标题
    top_color_height:app.globalData.navBarHeight,
    isWillExpire:false,
    authVisible:false,
  },
  onLoad() {

  },
  onShow() {
    wx.showShareMenu();
    // 查看是否授权
    this.queryUser();
    this.getCanUseCouponSize(wx.getStorageSync('userInfo').id);

  },
  goVipCneter(){
       wx.navigateTo({
        url:"/pages/vip/index"
       })
  },
  getCanUseCouponSize(userId){
    
    WXAPI.queryCouponsByUser(userId,{
      current_no:0,
      page_size:10,
      status:1
    }).then(res=> {
      var coupons = res;
      if(coupons.length>0)
         {
          this.setData({
             haveCoupons:true
          })
         }

      wx.hideNavigationBarLoading();
    }).catch((e) => {
      wx.hideNavigationBarLoading();
    });
  },
  goMap(e) {
    
    var typeMap = {
      "1": "/pages/order/index",
      "2": "/pages/buy-vip/index",
      "3": "/pages/mycoupons/index",
      "4": "/pages/appointment/index",
      "5": "/pages/wait-settlement/index",
      "6": "/pages/recharge/index",
      "7": "/pages/user-manage/index",
      // "8": "/pages/endvenue/index",
    }
    wx.navigateTo({
      url: typeMap[e.target.id]
    })

  },
  tapUserTop(){
    if(this.data.userInfo.id==undefined){
      this.setData({
        authVisible:true
      })
    }
  },
  
  queryUser() {

    

    WXAPI.queryUser().then(res=> {
      var userInfo = res;
      //TODO test
      if(userInfo==undefined || userInfo==''){
        this.setData({
          authVisible:true,
          userInfo:{
            nick_name: "微信用户",
            avatar_url: defaultAvatarUrl
          }
           
         });
          return;
      }
      var vip_expire_time=userInfo.vip_expire_time;
      userInfo.vip_expire_time=dateUtil.toDateShort(userInfo.vip_expire_time)
       
      this.setData({
        userInfo: userInfo,
        isVip: userInfo.vip,
        isManager: userInfo.admin,
        isWillExpire:dateUtil.isNowNear(vip_expire_time,7)
      });
      wx.setStorageSync("userInfo",userInfo);

      wx.hideNavigationBarLoading();
    }).catch((e) => {
      wx.hideNavigationBarLoading();
    });

  },

  toPayTap: function (e) {
    
    const orderId = e.currentTarget.dataset.id;
    let money = e.currentTarget.dataset.money;
    WXAPI.userAmount(wx.getStorageSync('token')).then(res=> {
      if (res.code == 0) {
        let _msg = '订单金额: ' + money + ' 元'
        if (res.data.balance > 0) {
          _msg += ',可用余额为 ' + res.data.balance + ' 元'
          if (money - res.data.balance > 0) {
            _msg += ',仍需微信支付 ' + (money - res.data.balance) + ' 元'
          }
        }
        money = money - res.data.balance
        wx.showModal({
          title: '请确认支付',
          content: _msg,
          confirmText: "确认支付",
          cancelText: "取消支付",
          success: res=> {
            console.log(res);
            if (res.confirm) {
              this._toPayTap(orderId, money)
            } else {
              console.log('用户点击取消支付')
            }
          }
        });
      } else {
        wx.showModal({
          title: '错误',
          content: '无法获取用户资金信息',
          showCancel: false
        })
      }
    })
  },
  _toPayTap: function (orderId, money) {
    const _this = this
    if (money <= 0) {
      // 直接使用余额支付
      WXAPI.orderPay(orderId, wx.getStorageSync('token')).then(res=> {
        _this.onShow();
      })
    } else {
      wxpay.wxpay('order', money, orderId, "/pages/order-list/index");
    }
  }
})